package com.cantor.provider.handler;

import com.cantor.core.message.PingMessage;
import com.cantor.core.message.PongMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * Ping心跳包处理器
 * 负责接收Ping心跳包并回复Pong心跳包, 以及处理读空闲事件
 */
@Slf4j
@ChannelHandler.Sharable
public class PingHandler extends SimpleChannelInboundHandler<PingMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PingMessage ping) throws Exception {
        log.debug("{} <<< PING <<< {}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
        ctx.writeAndFlush(new PongMessage()).addListener(f->{
            if(f.isSuccess()){
                log.debug("{} >>> PONG >>> {}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
            }
        });
    }

    // 读空闲处理
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            switch (((IdleStateEvent)evt).state()){
                case READER_IDLE:
                    log.error("服务器{}触发读空闲事件, 已关闭与{}的连接");
                    ctx.close();
                    break;
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }
}
